package cn.edu.sdjzu.xg.bysj.dao;

import cn.edu.sdjzu.xg.bysj.domain.Department;
import cn.edu.sdjzu.xg.bysj.domain.School;
import cn.edu.sdjzu.xg.bysj.service.DepartmentService;
import cn.edu.sdjzu.xg.bysj.service.SchoolService;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.TreeSet;

public final class DepartmentDao {
    private static DepartmentDao departmentDao = new DepartmentDao();

    private DepartmentDao() {
    }

    public static DepartmentDao getInstance() {
        return departmentDao;
    }

    public static Collection<Department> findAll(Connection connection , List conditions_json_str, Pagination pagination) throws SQLException {
        Collection<Department> departments = new TreeSet<Department>();
        int totalNum = CommonDao.getInstance().count(connection,"department");
        //创建查询的主语句
        StringBuilder sql_select = new StringBuilder("SELECT * FROM department ");
        //如果有条件，则生成条件子句，并附加到主语句后面
        if(conditions_json_str!=null){
            String whereClause = Condition.toWhereClause(conditions_json_str);
            sql_select.append(whereClause);
        }
        if(pagination!=null){
            String LimitClause = pagination.toLimitClause(totalNum);
            sql_select.append(LimitClause);
        }

        System.out.println(sql_select.toString());
        //获得查询的预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(sql_select.toString());
        //执行sql查询语句并获得结果集对象
        ResultSet resultSet = pstmt.executeQuery();
        //遍历结果集，根据元组创建对象，并添加到集合中
        while(resultSet.next()){
            departments.add(new Department(resultSet.getInt("id"),
                    resultSet.getString("description"),
                    resultSet.getString("no"),
                    resultSet.getString("remarks"),
                    SchoolService.getInstance().find(resultSet.getInt("school_id"))
            ));
        }
        JdbcHelper.close(resultSet,pstmt);
        return departments;
    }

    public static Department find(int id, Connection connection) throws SQLException {
        //创建sql语句
        String find_sql = "select * from department where id = ?";
        //在该连接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(find_sql);
        //为预编译参数赋值
        pstmt.setInt(1,id);
        //根据id查找
        ResultSet resultSet = pstmt.executeQuery();
        resultSet.next();
        Department department = new Department(id,
                resultSet.getString("description"),
                resultSet.getString("no"),
                resultSet.getString("remarks"),
                SchoolService.getInstance().find(resultSet.getInt("school_id"))
        );
        JdbcHelper.close(resultSet,pstmt);
        return department;
    }

    public static boolean update(Department department,Connection connection) throws SQLException {

        //创建sql语句
        String update_sql = "update department set description=?,no=?,remarks=? ,school_id=? where id=?";
        //在该链接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(update_sql);
        //为预编译参数赋值
        pstmt.setString(1,department.getDescription());
        pstmt.setString(2,department.getNo());
        pstmt.setString(3,department.getRemarks());
        pstmt.setInt(4,department.getSchool().getId());
        pstmt.setInt(5,department.getId());
        //根据执行结果，具体判断所要返回的值
        if (pstmt.executeUpdate()==0){
            JdbcHelper.close(null,pstmt);
            return false;
        }else
            JdbcHelper.close(null,pstmt);
            return  true;
    }

    public static boolean add(Department department, Connection connection) throws SQLException {

        //创建sql语句
        String add_sql =
                "insert into department (description,no,remarks,school_id) values " +
                        "(?,?,?,?);";
        //在该链接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(add_sql);
        //为预编译参数赋值

        pstmt.setString(1,department.getDescription());
        pstmt.setString(2,department.getNo());
        pstmt.setString(3,department.getRemarks());
        pstmt.setInt(4,department.getSchool().getId());
        //获取执行结果
        int affectedRowNum = pstmt.executeUpdate();
        //根据结果，具体判断所要返回的值
        if (affectedRowNum == 1) {
            JdbcHelper.close(null,pstmt);
            return true;
        } else
            JdbcHelper.close(null,pstmt);
            return false;
    }

    public static boolean delete(int id, Connection connection) throws SQLException{

        //创建sql语句
        String delete_sql = "DELETE FROM department WHERE id=?";
        //在该连接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(delete_sql);
        //为预编译参数赋值
        pstmt.setInt(1,id);

        if (pstmt.executeLargeUpdate() == 1){
            //关闭连接
            JdbcHelper.close(null,pstmt);
            return true;
        }else {
            //关闭连接
            JdbcHelper.close(null,pstmt);
            return false;
        }
    }
    public boolean delete(Department department, Connection connection) throws SQLException {

        String delete_sql = "delete from department where no = ?";
        //在连接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(delete_sql);
        //为预编译参数赋值
        pstmt.setString(1, department.getNo());
        //根据id删除 并判断是否删除成功
        if (pstmt.executeUpdate() == 0) {
            JdbcHelper.close(null,pstmt);
            return false;
        } else {
            JdbcHelper.close(null,pstmt);
            return true;
        }
    }

  public static int countAll(School school) throws SQLException {
      Connection connection = JdbcHelper.getConn();
      PreparedStatement pstmt = connection.prepareStatement("SELECT COUNT(id) as cnt_by_school FROM department WHERE school_id=?");
      pstmt.setInt(1,school.getId());
      ResultSet resultSet = pstmt.executeQuery();
      resultSet.next();
      int result = resultSet.getInt("cnt_by_school");
      JdbcHelper.close(resultSet,pstmt,connection);
      return result;
    }

}
